//
//  MineViewController.m
//  DongChiDaChiProject1
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "MineViewController.h"
#import "CollectViewController.h"
#import "DeclareViewController.h"
#import "AboutOurViewController.h"
#import "MineTableViewCell.h"
#import "TransitionViewController.h"
#import "LoginViewController.h"
#import "UserManager.h"
#import <AVOSCloud/AVOSCloud.h>

@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *cellTextArray;

// 定义一个属性判断是否是夜间模式
@property (nonatomic, assign) BOOL isYeJian;

// 定义一个view来弹出夜间模式框
@property (nonatomic, strong) UIView *yeJianView;

// 月亮
@property (nonatomic, strong) UIImageView *yueLiangImage;

// 太阳
@property (nonatomic, strong) UIImageView *taiYangImage;

// 定义一个属性判断黑几次
@property (nonatomic, assign) NSInteger heiCount;

// 收回
@property (nonatomic, assign) BOOL isReturn;

// 登陆按钮
@property (nonatomic, strong) UIButton *loginButton;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithHue:0.1 saturation:0.3 brightness:1 alpha:1]];
    [self.navigationController.navigationBar setTranslucent:NO];
    //self.view.backgroundColor = [[UIColor greenColor]colorWithAlphaComponent:0.2];
    self.title = @"我的";
    self.navigationController.navigationBar.translucent = NO;
    [self addSubView];
//    [self rightBarButton];
    [self addSubTableView];
    
    // 给isYeJian赋初值
    _isYeJian = NO;
    _isReturn = YES;
    _heiCount = 0;
    
    [self addYejian];

    
}

#pragma mark - 添加bar
- (void)addBarWithTitle:(NSString *)title
{
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(loginOrCancel:)];
    rightItem.tintColor = [UIColor colorWithHue:0.8 saturation:1 brightness:0.7 alpha:1];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)loginOrCancel:(UIBarButtonItem *)barItem
{
    if ([barItem.title isEqualToString:@"登录"]) {
        // 跳转到登陆页面
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    } else {
        // 注销账户
        [AVUser logOut];
        [[UserManager shareUserManagerHandle] saveUserName:@""];
        [[UserManager shareUserManagerHandle] saveIsLogined:@"NO"];
        self.navigationItem.title = @"我的";
        [barItem setTitle:@"登录"];
    }
}

#pragma mark - 添加夜间view
- (void)addYejian
{
    
    
    self.yeJianView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 115 * kWidthFitParameter)];
    self.yeJianView.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.1];
    [self.view addSubview:_yeJianView];
    
    // 在yejianview上添加image
    self.yueLiangImage = [[UIImageView alloc] initWithFrame:CGRectMake(50 * kWidthFitParameter, 20 * kWidthFitParameter, 70 * kWidthFitParameter, 70 * kWidthFitParameter)];
    self.yueLiangImage.layer.cornerRadius = self.yueLiangImage.width / 2;
    self.yueLiangImage.layer.masksToBounds = YES;
    self.yueLiangImage.tag = 600;
    self.yueLiangImage.userInteractionEnabled = YES;
    self.yueLiangImage.image = [UIImage imageNamed:@"yueliang1.jpg"];
    [self.yeJianView addSubview:_yueLiangImage];
    
    // 添加手势
    UITapGestureRecognizer *yueLiangTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionToYueLiang:)];
    [self.yueLiangImage addGestureRecognizer:yueLiangTapGes];
    
    
    
    self.taiYangImage = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth - 120 * kWidthFitParameter, 20 * kWidthFitParameter, 70 * kWidthFitParameter, 70 * kWidthFitParameter)];
    self.taiYangImage.layer.cornerRadius = self.taiYangImage.width / 2;
    self.taiYangImage.layer.masksToBounds = YES;
    self.taiYangImage.tag = 601;
    self.taiYangImage.userInteractionEnabled = YES;
    self.taiYangImage.image = [UIImage imageNamed:@"taiyang1.jpg"];
    [self.yeJianView addSubview:_taiYangImage];
    
    UITapGestureRecognizer *taiYangTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionToYueLiang:)];
    [self.taiYangImage addGestureRecognizer:taiYangTapGes];
    
    
    
}

#pragma mark - 图片的手势
- (void)actionToYueLiang:(UITapGestureRecognizer *)tapGes
{
    if (tapGes.view.tag == 600) {
        // 月亮
        // 需要开启夜间
        _heiCount++;
        NSLog(@"_heiCount = %ld", _heiCount);
        if (_heiCount == 1) {
            UIView *blackView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
            blackView.backgroundColor = [UIColor colorWithHue:0 saturation:0 brightness:0 alpha:0.3];
            blackView.userInteractionEnabled = NO;
            blackView.tag = 500;
            [[UIApplication sharedApplication].keyWindow addSubview:blackView];
         
            
        }
        // 返回
        [UIView animateWithDuration:0.5 animations:^{
            self.yeJianView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 115 * kWidthFitParameter);
        }];
        _isReturn = YES;
    } else if (tapGes.view.tag == 601) {
        // 太阳
        // 关闭夜间模式
        for (id tempView in [UIApplication sharedApplication].keyWindow.subviews) {
                            if ([tempView isKindOfClass:[UIView class]]) {
                                UIView *view = (UIView *)tempView;
                                if (view.tag == 500) {
                                   [view removeFromSuperview];
                               
                                }
                                
                            }
                        }
        _heiCount = 0;
        _isReturn = YES;
        // 返回
        [UIView animateWithDuration:0.5 animations:^{
            self.yeJianView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 115 * kWidthFitParameter);
        }];
        
    }
    
}

#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
    NSString *isLogin = [[UserManager shareUserManagerHandle] getIsLogined];
    if ([isLogin isEqualToString:@"YES"]) {
        // 说明登陆了
        [self addBarWithTitle:@"注销"];
        self.navigationItem.title = [NSString stringWithFormat:@"当前用户:%@", [[UserManager shareUserManagerHandle] getUserName]];
    } else {
        // 说明未登录
        [self addBarWithTitle:@"登录"];
        
    }
    
    self.tabBarController.tabBar.hidden = NO;
}

// 初始化self.tableView
- (void)addSubTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScreenHeight / 3, kScreenWidth, 200) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
}

- (void)addSubView
{
    UIImageView *loginImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight / 3)];
    loginImage.image = [UIImage imageNamed:@"mineBGimage.JPG"];
//    loginImage.userInteractionEnabled = YES;
//    self.loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    self.loginButton.frame = CGRectMake((kScreenWidth - 100 * kWidthFitParameter) / 2, 160 * kWidthFitParameter, 100 *kWidthFitParameter, 30 * kWidthFitParameter);
//    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
//    [self.loginButton addTarget:self action:@selector(actionToLoginPage:) forControlEvents:UIControlEventTouchUpInside];
//    self.loginButton.backgroundColor = [UIColor redColor];
//    
//    [loginImage addSubview:_loginButton];
    [self.view addSubview:loginImage];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MineCell";
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[MineTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    //cell.backgroundColor = [[UIColor greenColor]colorWithAlphaComponent:0.2];
    self.cellTextArray = @[@"我的收藏", @"清除缓存", @"免责声明", @"关于我们", @"模式转换"];
    NSArray *array = @[@"mine1.png", @"mine2.png", @"mine3.png", @"mine4.png", @"mine5.png"];
    for (int i = 0; i < self.cellTextArray.count; i++) {
        if (indexPath.row == i) {
            cell.cellName.text = self.cellTextArray[i];
            cell.cellImage.image = [UIImage imageNamed:array[i]];
        }
    }
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        // 收藏界面
        CollectViewController *collectVC = [[CollectViewController alloc] init];
        collectVC.titleName = self.cellTextArray[indexPath.row];
        [self.navigationController pushViewController:collectVC animated:YES];
    } else if (indexPath.row == 1) {
        // 清除缓存
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否清除缓存" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
      
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
            // 计算缓存的大小
            float folderSize;
            folderSize = [[SDImageCache sharedImageCache] getSize] / 1024.0 / 1024.0;
            NSLog(@"folderSize = %f", folderSize);
            NSString *cacheSize = [NSString stringWithFormat:@"清除了%.2fM缓存", folderSize];
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"通知" message:cacheSize delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [alertview show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alertview dismissWithClickedButtonIndex:0 animated:YES];
            });
            // 清除缓存
            [[SDImageCache sharedImageCache] clearDisk];
            /* 清除缓存
            NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            // 得到sdimage缓存的文件夹
            NSString *defaultString = [caches stringByAppendingPathComponent:@"default"];
            NSString *sdImageCache = [defaultString stringByAppendingPathComponent:@"com.hackemist.SDWebImageCache.default"];
           // NSLog(@"sdImageCache = %@", sdImageCache);
            NSFileManager *manager = [NSFileManager defaultManager];
            [manager removeItemAtPath:sdImageCache error:nil];
            */
           
            
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if (indexPath.row == 2) {
        // 免责声明
        DeclareViewController *declareVC = [[DeclareViewController alloc] init];
        declareVC.titleName = self.cellTextArray[indexPath.row];
        [self.navigationController pushViewController:declareVC animated:YES];
    } else if (indexPath.row == 3) {
        // 关于我们
        AboutOurViewController *aboutVC = [[AboutOurViewController alloc] init];
        aboutVC.titleName = self.cellTextArray[indexPath.row];
        [self.navigationController pushViewController:aboutVC animated:YES];
    } else {
        // 模式转换
//        TransitionViewController *transitionVC = [[TransitionViewController alloc] init];
//        transitionVC.titleName = self.cellTextArray[indexPath.row];
//        [self.navigationController pushViewController:transitionVC animated:YES];
//        UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
//        UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
//        blackView.backgroundColor = [UIColor colorWithHue:0 saturation:0 brightness:0 alpha:0.3];
//        blackView.userInteractionEnabled = NO;
//        [window addSubview:blackView];
//        if (_isYeJian == NO) {
//            // 需要开启夜间
//            UIView *blackView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//            blackView.backgroundColor = [UIColor colorWithHue:0 saturation:0 brightness:0 alpha:0.3];
//            blackView.userInteractionEnabled = NO;
//            blackView.tag = 500;
//            [[UIApplication sharedApplication].keyWindow addSubview:blackView];
//            _isYeJian = YES;
//        } else if (_isYeJian == YES) {
//            // 需要关闭夜间模式
//            for (id tempView in [UIApplication sharedApplication].keyWindow.subviews) {
//                if ([tempView isKindOfClass:[UIView class]]) {
//                    UIView *view = (UIView *)tempView;
//                    if (view.tag == 500) {
//                       [view removeFromSuperview];
//                     //   break;
//                    }
//                    
//                }
//            }
//            
//            _isYeJian = NO;
//        }
        if (_isReturn == YES) {
            [UIView animateWithDuration:0.5 animations:^{
                self.yeJianView.frame = CGRectMake(0, kScreenHeight - 215 * kWidthFitParameter, kScreenWidth, self.yeJianView.height);
            } completion:^(BOOL finished) {
                
            }];
            _isReturn = NO;
        } else if (_isReturn == NO) {
            [UIView animateWithDuration:0.5 animations:^{
                self.yeJianView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 115 * kWidthFitParameter);
            }];
            _isReturn = YES;
        }
      
        
        
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
